using UnityEngine;

public class PoolEntity:IPoolObject
{
    private ICachePool _cachePool;
    private GameObject _gameObject;

    public void TurnOn()
    {
        if (IsTurnOn) return;
        IsTurnOn = true;
        _gameObject.SetActive(true);
        OnTurnOnHandle();
    }

    public void TurnOff()
    {
        IsTurnOn = false;
        _gameObject.SetActive(false);
        OnTurnOffHandle();
    }

    public void SetObject(GameObject target)
    {
        _gameObject = target;
    }

    public void SetOwner(ICachePool pool)
    {
        _cachePool = pool;
    }

    public void SetParent(Transform value)
    {
        if (_gameObject != null && _gameObject.transform.parent != value)
        {
            _gameObject.transform.SetParent(value);
        }
    }

    public void DestroySelf()
    {
        if (_gameObject != null) GameObject.Destroy(_gameObject);
        if (_cachePool != null)
        {
            _cachePool.RemoveBy(this);
            _cachePool = null;
        }
        else
        {
            CachePoolManager.Remove(this);
        }
    }
    
    /// <summary>
    /// 被回收
    /// </summary>
    public void Recycle()
    {
        if (_cachePool != null) _cachePool.RecycleBy(this);
        else
        {
            CachePoolManager.RecycleOne(this);
        }
        
    }

    /// <summary>
    /// 获取对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public T GetComponent<T>()
    {
        return _gameObject.GetComponent<T>();
    }

    /// <summary>
    /// 获取gameObject
    /// </summary>
    public GameObject gameObject
    {
        get { return _gameObject; }
    }

    public bool IsTurnOn { get; set; }
    virtual protected void OnTurnOnHandle(){}
    virtual protected void OnTurnOffHandle(){}
}